package cn.ycc1.core.api;

import lombok.Builder;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title:
 * @Author ycc
 * @Date 2023/7/8 8:13
 */
@Data
@Builder
public class ApiResult<T> implements Serializable {

    public int code; // 返回状态码200成功
    private String msg; // 返回描述信息
    private T data; // 返回内容体

//    public static ApiResult<Boolean> result(boolean flag){
//        if (flag){
//            return ok();
//        }
//        return fail();
//    }

    public static ApiResult<Boolean> result(ApiCode apiCode){
        return result(apiCode,null);
    }
    public static <T> ApiResult<T> result(ApiCode apiCode, T data){
        return result(apiCode,null,data);
    }
    public static <T> ApiResult<T> result(ApiCode apiCode, String message, T data){
        boolean success = false;
        if (apiCode.getCode() == ApiCode.SUCCESS.getCode()){
            success = true;
        }
        if (StringUtils.isBlank(message)){
            message = apiCode.getMessage();
        }
        return (ApiResult<T>) ApiResult.builder()
                .code(apiCode.getCode())
                .msg(message)
                .data(data)
                .build();
    }

    public static ApiResult<Boolean> ok(){
        return ok(null);
    }
    public static <T> ApiResult<T> ok(T data){
        return result(ApiCode.SUCCESS,data);
    }
    public static <T> ApiResult<T> ok(T data, String message){
        return result(ApiCode.SUCCESS,message,data);
    }
//    public static ApiResult<Map<String,Object>> okMap(String key, Object value){
//        Map<String,Object> map = new HashMap<>(1);
//        map.put(key,value);
//        return ok(map);
//    }
    public static ApiResult<Boolean> fail(ApiCode apiCode){
        return result(apiCode,null);
    }
    public static ApiResult<String> fail(String message){
        return result(ApiCode.FAIL,message,null);
    }
//    public static <T> ApiResult<T> fail(ApiCode apiCode, T data){
//        if (ApiCode.SUCCESS == apiCode){
//            throw new RuntimeException("失败结果状态码不能为" + ApiCode.SUCCESS.getCode());
//        }
//        return result(apiCode,data);
//    }
//    public static <T> ApiResult<T> fail(Integer errorCode, String message){
//        return (ApiResult<T>) ApiResult.builder()
//                .code(errorCode)
//                .msg(message)
//                .build();
//    }

//    public static ApiResult<Map<String,Object>> fail(String key, Object value){
//        Map<String,Object> map = new HashMap<>(1);
//        map.put(key,value);
//        return result(ApiCode.FAIL,map);
//    }
    public static ApiResult<Boolean> fail() {
        return fail(ApiCode.FAIL);
    }
}
